import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 应用状态
  const loading = ref(false)
  const sidebarCollapsed = ref(false)
  const theme = ref('light')
  const language = ref('zh-CN')
  
  // 系统信息
  const systemInfo = ref({
    version: '1.0.0',
    buildTime: new Date().toISOString(),
    environment: import.meta.env.MODE
  })
  
  // 通知消息
  const notifications = ref([])
  const unreadCount = computed(() => 
    notifications.value.filter(n => !n.read).length
  )
  
  // 页面缓存
  const cachedPages = ref(new Set())
  
  // 设置加载状态
  const setLoading = (status) => {
    loading.value = status
  }
  
  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  // 设置主题
  const setTheme = (newTheme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
  }
  
  // 设置语言
  const setLanguage = (newLanguage) => {
    language.value = newLanguage
    localStorage.setItem('language', newLanguage)
  }
  
  // 添加通知
  const addNotification = (notification) => {
    const id = Date.now()
    notifications.value.unshift({
      id,
      timestamp: new Date(),
      read: false,
      ...notification
    })
    
    // 限制通知数量
    if (notifications.value.length > 50) {
      notifications.value = notifications.value.slice(0, 50)
    }
  }
  
  // 标记通知为已读
  const markNotificationAsRead = (id) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }
  
  // 清除所有通知
  const clearNotifications = () => {
    notifications.value = []
  }
  
  // 添加页面缓存
  const addCachedPage = (pageName) => {
    cachedPages.value.add(pageName)
  }
  
  // 移除页面缓存
  const removeCachedPage = (pageName) => {
    cachedPages.value.delete(pageName)
  }
  
  // 清除所有缓存
  const clearAllCache = () => {
    cachedPages.value.clear()
  }
  
  // 初始化应用设置
  const initApp = () => {
    // 从localStorage恢复设置
    const savedTheme = localStorage.getItem('theme')
    const savedLanguage = localStorage.getItem('language')
    const savedSidebarState = localStorage.getItem('sidebarCollapsed')
    
    if (savedTheme) theme.value = savedTheme
    if (savedLanguage) language.value = savedLanguage
    if (savedSidebarState) sidebarCollapsed.value = JSON.parse(savedSidebarState)
  }
  
  // 保存侧边栏状态
  const saveSidebarState = () => {
    localStorage.setItem('sidebarCollapsed', JSON.stringify(sidebarCollapsed.value))
  }
  
  return {
    // 状态
    loading,
    sidebarCollapsed,
    theme,
    language,
    systemInfo,
    notifications,
    unreadCount,
    cachedPages,
    
    // 方法
    setLoading,
    toggleSidebar,
    setTheme,
    setLanguage,
    addNotification,
    markNotificationAsRead,
    clearNotifications,
    addCachedPage,
    removeCachedPage,
    clearAllCache,
    initApp,
    saveSidebarState
  }
})
